<template>
  <div class="container">
    <div class="query-form">
      <el-form ref="formRef" :model="queryForm" :rules="rules" inline>
        <el-form-item label="日期" prop="date">
          <el-date-picker
            :disabled="true"
            v-model="queryForm.date"
            :clearable="false"
            type="date"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryForm.status" :disabled="true">
            <el-option label="待支付" value="待支付" />
            <el-option label="待送达" value="待送达" />
            <el-option label="已完成" value="已完成" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQueryClick">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table v-loading="isLoading" :data="orders" border>
      <el-table-column label="订单ID" prop="new_orderid" />
      <el-table-column label="客户电话" prop="phone" />
      <el-table-column label="订单类型" prop="ordertype" />
      <el-table-column label="配送地址" prop="addressname" />
      <el-table-column label="最终价格" prop="finallprice" />
      <el-table-column label="商品列表">
        <template #default="{ row }">
          {{ mealListToString(row.meal_list) }}
        </template>
      </el-table-column>
      <el-table-column label="备注">
        <template #default="{ row }">
          {{ row.note ? row.note : "None" }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <!-- <el-button
            v-if="row.orderstatus === '待送达'"
            size="small"
            type="primary"
            @click="handlePrintClick(row)"
          >
            打印
          </el-button> -->

          <el-button
            v-if="row.orderstatus === '待送达'"
             size="small"
            @click="handleDeliveredConfirm(row.id)"
            type="primary"
          >
            已送达
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div id="print-area" ref="printDom">
      <div
        v-for="(item, index) in selectdataMune"
        :key="index"
        style="page-break-after: always"
      >
        <div>
          <span>配送地点：</span>
          <span>{{ item?.addressname }}</span>
        </div>
        <div>
          <span>订单尾号：</span>
          <span>{{ phoneWithLast4Chars(item.new_orderid as string)  }}</span>
        </div>
        <!-- <div>
          <span>用户昵称：</span>
          <span>{{ item?.id }}</span>
        </div> -->
        <div>
          <span>手机尾号：</span>
          <span v-if="item?.phone !== undefined">{{
            phoneWithLast4Chars(item.phone)
          }}</span>
        </div>
        <div>
          <span>订餐日期：</span>
          <span>{{ String(item?.createtime).split(" ")[0] || "" }}</span>
        </div>
        <table class="meal-table">
          <tbody>
            <tr v-for="(meal, index) in item?.meal_list" :key="index">
              <td class="name" style="width: 280px">
                <span>餐品名称：{{ meal.name || "无" }}</span>
              </td>
              <td>
                <div>
                  <span>X{{ meal.count }}</span>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        <div>
          <span>生产日期：</span>
          <span>{{ item?.pstime }}</span>
        </div>
        <div>
          <span>保质期：建议四小时内食用完</span>
        </div>

        <span v-for="n in 40" :key="n">-</span>
        <!-- <div style="height: 30px"></div> -->
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { nextTick, ref, onMounted, watch, onBeforeUnmount } from "vue";
import OrderResponse from "@/api/types/order/OrderResponse";
import print from "print-js";
import { ElForm, ElMessage, FormRules } from "element-plus";
import { getOrdersByDateAndStatus, updateOrderStatusToDelivered } from "@/api/order";
import { isAxiosError } from "axios";
import { formatDate } from "@/utils/date";
import { MealResponse } from "@/api/types/meal";
import { OrderStatus } from "@/api/types/order/OrderStatus";

const queryForm = ref<{ date: string; status: OrderStatus }>({
  date: formatDate(new Date()),
  status: "待送达",
});
const formRef = ref<InstanceType<typeof ElForm>>();
const isLoading = ref(false);
const orders = ref<OrderResponse[]>([]);
const currentPrintOrder = ref<OrderResponse>();
const printDom = ref<HTMLDivElement>();

const rules: FormRules = {
  date: [
    {
      required: true,
      message: "请选择日期",
      trigger: "change",
    },
  ],
  status: [
    {
      required: true,
      message: "请选择 ",
      trigger: "change",
    },
  ],
};

async function getData() {
  if (isLoading.value == false) {
    isLoading.value = true;
  }
  if (queryForm.value.date !== undefined) {
    const { result } = await getOrdersByDateAndStatus(
      queryForm.value.date,
      queryForm.value.status
    );
    if (result !== undefined) {
      orders.value = result;
      isLoading.value = false;
    }
  }
}

async function handleDeliveredConfirm(orderId: string) {
  const { code, msg } = await updateOrderStatusToDelivered([orderId]);
  if (code === "200") {
    ElMessage.success(msg);
    await getData();
  }
}

const selectdataMune = ref<OrderResponse[]>([]);

function handlePrintClick(row: OrderResponse) {
  console.log(row);
  selectdataMune.value = [];
  selectdataMune.value.push(row);
  if (selectdataMune.value.length <= 0) {
    ElMessage.error("请选择打印的数据");
    return;
  }

  nextTick(() => {
    if (printDom.value !== undefined) {
      printDom.value.style.display = "block";
      print({
        printable: "print-area",
        type: "html",
        documentTitle: "",
        targetStyles: ["*"],
        style: `body {zoom: 180%;}
        @media print{@page {size:landscape}}`,
      });
      printDom.value.style.display = "none";
    }
  });
}

// 首次查询待支付
onMounted(() => {
  handleQueryClick();
});

function getTargetDate() {
  const now = new Date();
  const hours = now.getHours();

  if (hours < 12) {
    // 如果当前时间在12点之前，则返回当天日期
    return new Date(now.getFullYear(), now.getMonth(), now.getDate());
  } else {
    // 如果当前时间在12点之后，则返回明天日期
    const tomorrow = new Date(now);
    tomorrow.setDate(tomorrow.getDate() + 1);
    return tomorrow;
  }
}

async function handleQueryClick() {
  formRef.value?.validate(async (isValid: boolean) => {
    const targetDate = getTargetDate();
    const formattedDate = `${targetDate.getFullYear()}-${String(
      targetDate.getMonth() + 1
    ).padStart(2, "0")}-${String(targetDate.getDate()).padStart(2, "0")}`;
    queryForm.value.date = formattedDate;

    if (isValid) {
      try {
        await getData();
      } catch (error) {
        if (isAxiosError(error) && error.response?.data.message != undefined) {
          ElMessage.error(error.response?.data.message);
        }
      }
    }
  });
}

async function fetchOrders() {
  try {
    await getData();
  } catch (error) {
    console.error("There was an error fetching the orders!", error);
  }
}

let timer: string | number | NodeJS.Timeout | undefined;

const startAutoRefresh = () => {
  clearInterval(timer);
  timer = setInterval(fetchOrders, 5000);
};

const stopAutoRefresh = () => {
  clearInterval(timer);
};

watch(
  () => queryForm.value.status,
  (newStatus) => {
    if (newStatus === "待送达") {
      startAutoRefresh();
    } else {
      stopAutoRefresh();
    }
  },
  {
    immediate: true,
  }
);

function mealListToString(mealList: MealResponse[]) {
  return mealList.map((meal) => `${meal.name}x${meal.count}`).join("、");
}

function phoneWithLast4Chars(phone: string) {
  return phone.slice(-4);
}

onBeforeUnmount(() => {
  stopAutoRefresh();
});
</script>
<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;

  .query-form {
    .el-select {
      --el-select-width: 240px;
    }
  }
}

#print-area {
  font-size: 16px;
  width: 320px;
  padding-left: 10px;
  display: none;
}
</style>
